package lisuli.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import lisuli.entity.User;
import lisuli.service.UserService;
import lisuli.util.JsonResult;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/account")
public class UserController {
	@Autowired
	private UserService userService;

	@RequestMapping("/regist.do")
	@ResponseBody
	public JsonResult regist(String username, String password) {
		try {
			User user = userService.regist(username, password);
			return new JsonResult(user);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new JsonResult(e);
		}

	}

	@RequestMapping("/login.do")
	@ResponseBody
	public JsonResult login(String username, String password) {
		try {
			User user = userService.login(username, password);
			return new JsonResult(user);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new JsonResult(e);
		}

	}

	// excel
	@RequestMapping(value = "excel.do", produces = "application/vnd.ms-excel")
	@ResponseBody
	public byte[] excel(HttpServletResponse response) throws IOException {

		response.setHeader("Content-Disposition",
				"attachment;filename=\"demo.xls\"");

		HSSFWorkbook book = new HSSFWorkbook();
		HSSFSheet sheet = book.createSheet("sheet1");
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell = row.createCell(0);
		cell.setCellType(HSSFCell.CELL_TYPE_STRING);
		cell.setCellValue("Hello World!");

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		book.write(out);
		out.close();
		byte[] data = out.toByteArray();
		return data;
	}
}
